<?php
namespace Home\Controller;

use Common\Controller\HomebaseController;
use Common\Model\MembersModel;
use Common\ModelSQ\ParkApi;
use Common\ModelSQ\ERPUser;
import('Common.WxPay.JsApiPay', APP_PATH, '.php');

class ParkController extends HomebaseController
{

    public function _initialize()
    {
        parent::_initialize();
    }

    //车辆列表
    public function MyCar()
    {
        $member = $this->getMember();
        if (!$member) {
            $this->redirect('public/login');
        }
        $cars = M('mycar')->where(array('telephone' => $member['telephone']))->select();
        $this->assign('cars', $cars);
        $this->display();
    }

    public function AddCar()
    {
        $carNo = I("post.carNo");
        $member = $this->getMember();
        if (!$member) {
            $this->ajaxReturn(array('code' => 400, 'message' => '请先登陆！'));
        }
        $carInfo = M('mycar')->where(array('carno' => $carNo, 'telephone' => $member['telephone']))->find();
        if ($carInfo) {
            $this->ajaxReturn(array('code' => 400, 'message' => '车辆信息已存在！'));
        }

        $car = array(
            'telephone' => $member['telephone'],
            'carno' => $carNo,
            'create_time' => date('Y-m-d H:i:s')
        );
        M('mycar')->add($car);
        $this->ajaxReturn(array('code' => 200, 'message' => 'succes'));
    }

    //解除车辆
    public function Reselase()
    {
        $carNo = I("post.carNo");
        $member = $this->getMember();
        if (!$member) {
            $this->ajaxReturn(array('code' => 400, 'message' => '请先登陆！'));
        }

        $carInfo = M('mycar')->where(array('carno' => $carNo, 'telephone' => $member['telephone']))->find();
        if (!$carInfo) {
            $this->ajaxReturn(array('code' => 400, 'message' => '车牌已解绑，请勿重复操作'));
        }
        M('mycar')->where(array('id' => $carInfo['id']))->delete();
        $this->ajaxReturn(array('code' => 200, 'message' => 'succes'));
    }

    //查询车牌是否入库
    public function Search()
    {
        $carNo = I("post.carNo");
        $config = C('PARK_API');
        $parkApi = new ParkApi();
        $data = array('code' => 400, 'message' => '');
        $p = array(
            'serviceId' => '3c.pay.querycarbycarno',
            'requestType' => 'DATA',
            "attributes" => array(
                'parkCode' => $config['parkCode'],
                'carNo' => $carNo,
            )
        );
        $result = $parkApi->request($p);
        if (isset($result['dataItems']) && is_array($result['dataItems'])) {
            foreach ($result['dataItems'] as $item) {
                if ($item['attributes']['carNo'] == $carNo) {
                    $data = array('code' => 200, 'message' => '');
                }
            }
        }
        $this->ajaxReturn($data);
    }

    //停车信息
    public function ParkInfo()
    {
        $carNo = I("get.carNo");
        $config = C('PARK_API');
        $parkApi = new ParkApi();
        $p = array(
            'serviceId' => '3c.pay.createorderbycarno',
            'requestType' => 'DATA',
            "attributes" => array(
                'businesserCode' => $config['businesserCode'],
                'parkCode' => $config['parkCode'],
                'orderType' => 'VNP',
                'carNo' => $carNo
            )
        );
        $result = $parkApi->request($p);
        $bill = $result['dataItems'][0]['attributes'];
        $erpUser = new ERPUser();
        $member = $this->getMember();
        $data = array('telephone' => $member['telephone']);
        $erp_userinfo = $erpUser->getMember($data);
        $point = $erp_userinfo['data']['member_bonus'];
        $rule = 1;
        $ruleArr = $erpUser->getIntegralRule(array('paraname' => 'Integraldeductionrule'));
        if (isset($ruleArr['data'][0]['paramvalue'])) {
            $v = $ruleArr['data'][0]['paramvalue'];
            $v = explode(':', $v);
            $rule = $v[1] / $v[0];
        }
        $bill['dikou']  =  ceil($bill['totalFee'] * $rule);
        $this->assign('bill', $bill);
        $this->assign('point', $point);
        $this->display();
    }

    //wx支付
    public function WxPay()
    {
        $carNo = I("get.carNo");
        $config = C('PARK_API');

        $parkApi = new ParkApi();
        $p = array(
            'serviceId' => '3c.pay.createorderbycarno',
            'requestType' => 'DATA',
            "attributes" => array(
                'businesserCode' => $config['businesserCode'],
                'parkCode' => $config['parkCode'],
                'orderType' => 'VNP',
                'carNo' => $carNo,
            )
        );

        $result = $parkApi->request($p);
        if (!$result || !isset($result['dataItems']) || !isset($result['dataItems'][0]['attributes'])) {
        }
        $bill = $result['dataItems'][0]['attributes'];
        $totalFee = $bill['totalFee']*100;
        //$totalFee = 1;
        try {

            $tools = new \JsApiPay();
            $openId = $tools->GetOpenid();

            //②、统一下单
            $input = new \WxPayUnifiedOrder();
            $input->SetBody("夏都小镇-停车");
            $input->SetAttach("停车费");
            $input->SetOut_trade_no($bill['orderNo']);
            $input->SetTotal_fee($totalFee);
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $input->SetGoods_tag("停车费");
            $input->SetNotify_url("http://town.lidoway.com/park/wxnotify");
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid($openId);
            $config = new \WxPayConfig();
            $order = \WxPayApi::unifiedOrder($config, $input);
            $jsApiParameters = $tools->GetJsApiParameters($order);
            $this->assign('jsApiParameters', $jsApiParameters);
            $this->assign('carNo', $carNo);
            $this->display('pay');

        } catch (Exception $e) {
            elog(json_encode($e));
        }
    }

    //wx支付回调
    public function WxNotify()
    {
        $config = new \WxPayConfig();
        if (isset($GLOBALS['HTTP_RAW_POST_DATA'])) {
            //如果返回成功则验证签名
            try {
                //获取通知的数据
                $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
                $result = \WxPayNotifyResults::Init($config, $xml);
                $result = $result->GetValues();

                if (array_key_exists("return_code", $result)
                    && array_key_exists("result_code", $result)
                    && $result["return_code"] == "SUCCESS"
                    && $result["result_code"] == "SUCCESS") {

                    $orderNo = explode('-',$result['out_trade_no']);
                    $parkApi = new ParkApi();
                    $p = array(
                        'serviceId' => '3c.pay.notifyorderresult',
                        'requestType' => 'DATA',
                        "attributes" => array(
                            'orderNo' => $orderNo[0],
                            'tradeStatus' => 0,
                            'payType' => 'WX',
                            'payTypeName' => '微信支付',
                        )
                    );
                    $res = $parkApi->request($p);
                }
            } catch (WxPayException $e) {
            }
        }
    }

    //积分支付
    public function PointPay()
    {
        $carNo = I("post.carNo");
        $config = C('PARK_API');
        $erpUser = new ERPUser();
        $memberModel = new MembersModel();

        $member = $this->getMember();
        $data = array('telephone' => $member['telephone']);
        $erp_userinfo = $erpUser->getMember($data);
        $point = $erp_userinfo['data']['member_bonus'];

        $rule = 1;
        $ruleArr = $erpUser->getIntegralRule(array('paraname' => 'Integraldeductionrule'));
        if (isset($ruleArr['data'][0]['paramvalue'])) {
            $v = $ruleArr['data'][0]['paramvalue'];
            $v = explode(':', $v);
            $rule = $v[1] / $v[0];
        }

        $parkApi = new ParkApi();
        $p = array(
            'serviceId' => '3c.pay.createorderbycarno',
            'requestType' => 'DATA',
            "attributes" => array(
                'businesserCode' => $config['businesserCode'],
                'parkCode' => $config['parkCode'],
                'orderType' => 'VNP',
                'carNo' => $carNo,
                'couponType' => 2,
                'couponValue' => 1,
            )
        );
        $result = $parkApi->request($p);
        if (!$result || !isset($result['dataItems']) || !isset($result['dataItems'][0]['attributes'])) {
            $this->ajaxReturn(array('code' => 400, 'message' => '数据有误，请返回重试！'));
        }

        $bill = $result['dataItems'][0]['attributes'];
        $usePoint = ceil($bill['totalFee'] * $rule);

        if ($bill['retcode'] == 9) {
            $this->ajaxReturn(array('code' => 400, 'message' => $bill['retmsg']));
        } elseif ($bill['retcode']) {
            $this->ajaxReturn(array('code' => 400, 'message' => '数据有误，请返回重试！'));
        }
        if ($point < $usePoint) {
            $this->ajaxReturn(array('code' => 400, 'message' => '积分不足！'));
        }

        $p = array(
            'serviceId' => '3c.pay.notifyorderresult',
            'requestType' => 'DATA',
            "attributes" => array(
                'orderNo' => $bill['orderNo'],
                'tradeStatus' => 0,
                'payType' => 'OTHER',
                'payTypeName' => '积分抵扣'
            )
        );
        $result = $parkApi->request($p);

        //同步ERP积分
        $request_params = array(
            'member_code' => $erp_userinfo['data']['member_code'],
            'bonus_date' => date('Y-m-d'),
            'bonus_time' => date('H:i:s'),
            'bonus_type' => '03',                        //积分消费
            'store_code' => $config['businesserCode'],   //商场编码
            'bonus_point' => 1,                          //扣减积分
            'store_name_sc' => '积分支付停车费',
            'bonus_description' => '积分支付停车费',
        );
        $erpUser->bonusSync($request_params);

        //扣减会员积分
        $memberModel->where(array('id' => $member['id']))->setDec('integral', $point - $usePoint);

        $this->ajaxReturn(array('code' => 200, 'message' => '积分不足！'));
    }



    /********************************************************************************/

    //停车
    public function Index()
    {
        $this->display();
    }

    //车牌缴费
    public function parkPayment(){
        $this->display();
    }

    public function Test(){
        $erpUser = new ERPUser();
        $member = $this->getMember();
        $data = array('telephone' => $member['telephone']);
        $erp_userinfo = $erpUser->getMember($data);
        elog($erp_userinfo);
        $point = $erp_userinfo['data']['member_bonus'];

        $config = C('PARK_API');
        $request_params = array(
            'member_code' => $erp_userinfo['data']['member_code'],
            'bonus_date' => date('Y-m-d'),
            'bonus_time' => date('H:i:s'),
            'bonus_type' => '03',                        //积分消费
            'store_code' => $config['businesserCode'],   //商场编码
            'bonus_point' => 1,                          //扣减积分
            'store_name_sc' => '积分支付停车费',
            'bonus_description' => '积分支付停车费',
        );
        $erpUser->bonusSync($request_params);

        $erp_userinfo = $erpUser->getMember($data);
    }

}


